<template>
    <div class="doc-form">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-menu"></i> 文档管理</el-breadcrumb-item>
                <el-breadcrumb-item v-if="isNew">文档添加</el-breadcrumb-item>
                <el-breadcrumb-item v-if="!isNew">文档编辑</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <el-form size="mini" ref="ruleForm" :model="form" :rules="rules" label-width="110px">
            <el-form-item label="栏目" prop="arttype">
                <el-cascader placeholder="请选择栏目"
                             v-model="form.arttype"
                             :options="arttypes"
                             :props="arttypeProps">
                </el-cascader>
            </el-form-item>
            <el-form-item label="标题" prop="arttitle">
                <el-input v-model="form.arttitle" placeholder="请输入标题" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="简短标题" prop="shorttitle">
                <el-input v-model="form.shorttitle" placeholder="请输入简短标题" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="来源" prop="source">
                <el-radio-group v-model="form.source">
                    <el-radio label="原创">原创</el-radio>
                    <el-radio label="转载">转载</el-radio>
                    <el-radio disabled label="用户发布">用户发布</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="是否显示" prop="showflag">
                <el-switch active-value="1" inactive-value="0" v-model="form.showflag"></el-switch>
            </el-form-item>
            <el-form-item label="发布状态" prop="deliver">
                <el-radio-group v-model="form.deliver">
                    <el-radio label="0">暂存</el-radio>
                    <el-radio label="1">发布</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="发布时间" prop="delivertime">
                <el-date-picker v-model="form.delivertime"
                                type="datetime"
                                placeholder="请选择发布时间"
                                default-time="12:00:00">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="标签/关键字" prop="keyword">
                <el-select v-model="form.keyword"
                           multiple
                           filterable
                           allow-create
                           default-first-option
                           placeholder="请选择文章标签">
                    <el-option v-for="item in keywords"
                               :key="item.value"
                               :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="摘要" prop="summay">
                <el-input type="textarea" v-model="form.summay" placeholder="请输入文章摘要"
                          auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="内容" prop="content">
                <UE ref="ue" :config="config" :defaultMsg="form.content" @ready="editorReady" v-if="isShow"></UE>
            </el-form-item>
            <el-form-item>
                <div class="fixed-btn">
                    <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
                    <el-button @click="goBack">取消</el-button>
                </div>
            </el-form-item>
        </el-form>
    </div>
</template>


<script>

  import UE from '@/components/common/UE.vue'

  export default {
    components: {UE},
    data: function () {
      return {
        isNew: false,
        isShow: false,
        form: {
          artid: '',           //文章id
          arttype: [],         //文章类型
          arttitle: '',        //标题
          shorttitle: '',      //简短标题
          source: '用户发布',   //来源(原创、转载)
          keyword: [],      //关键字
          summay: '',       //摘要
          content: '',      //内容
          author: sessionStorage.getItem("ms_username"),  //作者
          sortid: '1',      //排序编号
          deliver: '1',     //发布状态
          delivertime: '',  //发布时间
          audit: '0',       //审核状态
          showflag: '1',  //是否显示
        },
        rules: {
          arttype: [
            {required: true, message: '请选择栏目', trigger: 'blur'}
          ],
          arttitle: [
            {required: true, message: '请输入标题', trigger: 'blur'}
          ],
          shorttitle: [
            {required: true, message: '请输入简短标题', trigger: 'blur'}
          ],
          summay: [
            {required: true, message: '请输入文章摘要', trigger: 'blur'}
          ],
          content: [
            {required: true, message: '请输入文章内容', trigger: 'blur'}
          ],
          delivertime: [
            {required: true, message: '请选择发布时间', trigger: 'blur'}
          ]
        },
        keywords: [{
          value: '选项1',
        }, {
          value: '选项2',
        }, {
          value: '选项3',
        }, {
          value: '选项4',
        }],
        arttypeProps: {
          value: "catid",
          label: "catname",
          children: "children"
        },
        arttypes: [],
        config: {
          initialFrameHeight: 200,
        }
      }
    },
    methods: {
      editorReady(instance) {
        instance.addListener("contentChange", () => {
          this.form.content = instance.getContent();
        });
      },
      submitForm(ruleForm) {
        var self = this;
        self.$refs[ruleForm].validate((valid) => {
          if (valid) {
            var url = '';
            if (self.$route.path == '/document_add') {      //新增
              url = '/art/add';
            } else {     //编辑
              url = '/art/edit';
            }
            self.$axios.post(url, self.form)
              .then(function (res) {
                if (res.data.code == 0) {
                  self.goBack()
                } else {
                  self.$message.error(res.data.message);
                }
              })
              .catch(function (err) {
                self.$message.error('请求网络失败，请稍后再试！');
              })
          } else {
            return false;
          }
        })
      },
      goBack() {
        this.$router.go(-1);
      },
      //迭代删除空的指定属性
      deleteEmpty(arr, prop) {
        var self = this;
        for (var i = 0; i < arr.length; i++) {
          if (arr[i][prop].length == 0) {
            delete arr[i][prop]
          } else {
            self.deleteEmpty(arr[i][prop], prop)
          }
        }
      },
      //页面初始化
      getArticle(id) {
        var self = this
        self.$axios.post('/art/getArticle', {
          artid: id
        }).then(function (res) {
          if (res.data.code == 0) {
            self.form = res.data.data[0]
            self.form.keyword = self.form.keyword.trim() == '' ? [] : self.form.keyword.split(',')
            self.form.arttype = self.form.arttype.trim() == '' ? [] : self.form.arttype.split(',')
            // 为了保证内容获取到以后才进行ueditor的渲染
            self.isShow = true;
          } else {
            this.$message.error(res.data.message);
          }
        }).catch((err) => {
          this.$message.error('获取文章详情失败，请稍后再试！');
        })
      },
      getCategory() {
        let self = this
        self.$axios.post('/cat/getcatlist', {parentid: 'ROOT'}).then(function (res) {
          if (res.data.code == 0) {
            var arr = res.data.data;
            self.deleteEmpty(arr, 'children');
            self.arttypes = arr
          } else {
            self.$message.error(res.data.message);
          }
        }).catch((err) => {
          self.$message.error('获取文章栏目分类失败，请稍后再试！');
        })
      }
    },
    created() {
      if (this.$route.path == '/document_add') { //新增
        this.form.artid = 'id' + Math.random() * 100000000000000000
        this.isNew = true;
        this.isShow = true;
        this.getCategory()
      } else {        //编辑
        this.isNew = false;
        this.getArticle(this.$route.query.id)
        this.getCategory()
      }
    }
  }
</script>

<style scoped>
    .doc-form {
        width: 80%;
    }

    .fixed-btn {
        position: fixed;
        z-index: 9999999;
        padding: 10px 30px;
        text-align: right;
        right: 0;
        bottom: 0;
        background: none;
        margin-bottom: 0;
    }
</style>
